package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mark3labs/mcp-go/client"
	"github.com/mark3labs/mcp-go/mcp"
)

func main() {
	// 创建 Streamable HTTP 客户端
	client, err := client.NewStreamableHttpClient("http://localhost:8888/mcp")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// 启动客户端
	ctx := context.Background()
	if err := client.Start(ctx); err != nil {
		log.Fatalf("Failed to start client: %v", err)
	}

	// 初始化客户端
	initRequest := mcp.InitializeRequest{}
	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
	initRequest.Params.ClientInfo = mcp.Implementation{
		Name:    "test-client",
		Version: "1.0.0",
	}

	serverInfo, err := client.Initialize(ctx, initRequest)
	if err != nil {
		log.Fatalf("Failed to initialize: %v", err)
	}

	// 显示服务器信息
	fmt.Printf("Connected to server: %s (version %s)\n",
		serverInfo.ServerInfo.Name,
		serverInfo.ServerInfo.Version)
	fmt.Printf("Server capabilities: %+v\n", serverInfo.Capabilities)

	// 列出可用资源
	if serverInfo.Capabilities.Resources != nil {
		fmt.Println("Fetching available resources...")
		resourcesRequest := mcp.ListResourcesRequest{}
		resourcesResult, err := client.ListResources(ctx, resourcesRequest)
		if err != nil {
			log.Printf("Failed to list resources: %v", err)
		} else {
			fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
			for i, resource := range resourcesResult.Resources {
				fmt.Printf("  %d. %s - %s\n", i+1, resource.URI, resource.Name)
			}
		}

		// 读取资源
		if len(resourcesResult.Resources) > 0 {
			readRequest := mcp.ReadResourceRequest{}
			readRequest.Params.URI = resourcesResult.Resources[0].URI

			readResult, err := client.ReadResource(ctx, readRequest)
			if err != nil {
				log.Fatalf("Failed to read resource: %v", err)
			}

			fmt.Printf("Number of content items: %d\n", len(readResult.Contents))
			for _, content := range readResult.Contents {
				if textContent, ok := content.(mcp.TextResourceContents); ok {
					fmt.Printf("Resource content: %s\n", textContent.Text)
				}
			}
		}
	}
}
